import * as Cesium from "cesium/Cesium";
// import CesiumMeshVisualizer from 'cesiummeshvisualizer/Source/Main.js'
import GeoTIFF, { fromUrl, fromUrls, fromArrayBuffer, fromBlob } from "geotiff";
export const Mixins = {
  created() {},
  mounted() {},
  watch:{
    drillType:{
      handler(newVal){
        console.log(newVal,"drillType");        
      },
      immediate:true,
      deep:true
    },
    wellType:{
      handler(newVal){
        console.log(newVal,"wellType");
      },
      immediate:true,
      deep:true
    }
  },
  data() {
    return {
      checkedRemoteImage:"",
      // 左侧列表勾选的节点
      checkedNodeArr:[],
      // 存储左侧列表数据信息
      saveProjectListData: new Map(),
      // 存储列表类别对应的phase字段 - 方便调用数据接口
      saveCategoryPhase: new Map(),
      newBaseUrl: "http://47.119.187.14:9002/dt-api",
      // 左侧数据列表
      leftDataList: new Map(),
      // remote list
      remoteList: new Map(),
      // drill list
      drillList: new Map(),
      // ert list
      ertList: new Map(),
      // em list
      emList: new Map(),
      // terrain list
      terrainList: new Map(),
      // wellList
      wellList: new Map(),
      // 钻孔id - cesium entity
      drillId: new Map(),
      // ERT id - cesium entity
      ertId: new Map(),
      // em id - cesium entity
      emId: new Map(),
      // well id - cesium entity
      wellId: new Map(),
      // 污染物 id - ceisum entity
      pollutantId: new Map(),
      // 钻孔类型
      drillType:"rock",
      // 监测井类型
      wellType:"wellDepth",
      // MeshVisualizer:CesiumMeshVisualizer.MeshVisualizer,
      // Mesh:CesiumMeshVisualizer.Mesh,
      // FramebufferTexture:CesiumMeshVisualizer.FramebufferTexture,
      // GeometryUtils:CesiumMeshVisualizer.GeometryUtils,
      // PlaneBufferGeometry:CesiumMeshVisualizer.PlaneBufferGeometry,
      meshVisualizerTif:null
    };
  },
  methods: {
    /**
     * 切换钻孔类型
     */
    switchDrillType(data){
      if(data.rockChecked){
        this.drillType = "rock"
      }
      if(data.pollutantChecked){
        this.drillType = "pollutant"
      }
    },
    /**
     * 切换测井类型
     */
    switchWellType(data){
      if(data.wellDepthChecked){
        this.wellType = "wellDepth"
      }
      if(data.wellPollutantChecked){
        this.wellType="wellPollutant"
      }
    },
    /**
     * 添加精细化地形
     */
    addTerrain(data) {
      // debugger
      // let terrain = this.newBaseUrl +  data.remotepath
      // let image
      // const readGeoTif = function () {
      //   GeoTIFF.fromUrl(terrain).then(rawTiff => {
      //     return rawTiff.getImage();
      //   }).then(tifImage => {
      //     image = {
      //       width: tifImage.getWidth(),
      //       height: tifImage.getHeight(),
      //     };
      //     /*
      //     The third and fourth parameter are image segments and we are subtracting one from each,
      //      otherwise our 3D model goes crazy.
      //      https://github.com/mrdoob/three.js/blob/master/src/geometries/PlaneGeometry.js#L57
      //      */
      //     // const geometry = new Cesium.PlaneGeometry({
      //     //   positions: [Cesium.Cartesian3.fromDegrees(115.253962, 23.085151, 0), Cesium.Cartesian3.fromDegrees(115.253962, 23.085151, 0), Cesium.Cartesian3.fromDegrees(115.253962, 21.085151, 0), Cesium.Cartesian3.fromDegrees(113.253962, 21.085151, 0)]
      //     // });
      //     const bbox = tifImage.getBoundingBox();
      //     return tifImage.readRasters({
      //       interleave: true
      //       , bbox: bbox
      //     });
      //   }).then(data => {
      //     console.time('parseGeom');
      //     debugger
      //     var geometry = this.PlaneBufferGeometry.createGeometry(new this.PlaneBufferGeometry(
      //       image.width,
      //       image.height,
      //       image.width - 1,
      //       image.height - 1));
      //     this.GeometryUtils.rotateX(geometry, -Math.PI / 2);
      //     const arr1 = new Array(geometry.attributes.position.values.length);
      //     const arr = arr1.fill(1);
      //     var vertices = geometry.attributes.position.values;
      //     // arr.forEach((a, index) => {
      //     //   // geometry.attributes.position.setZ(index, (data[index] / 10) * -1);
      //     //   geometry.attributes.position.values[index] = (data[index] * 100000) * -1;
      //     // });
      //     for (var i = 0, j = 0, l = vertices.length; i < l; i++, j += 3) {
      //       // j + 1 because it is the y component that we modify
      //       vertices[j + 1] = (data[i] * 10);
      //     }
      //     // geometry.computeVertexNormals();
      //     this.GeometryUtils.computeVertexNormals(geometry);
      //     console.timeEnd('parseGeom');
      //     // const texture = new Cesium.TextureLoader().load('http://192.168.2.81:5503/data/dem/agri-medium-autumn.jpg');
      //     const material = new CesiumMeshVisualizer.MeshPhongMaterial({
      //       wireframe: false,
      //       side: this.MeshMaterial.Sides.BACK,
      //       // map: texture,
      //       defaultColor: "rgb(125,125,125)",
      //       translucent: true
      //     });
      //     const mountain = new this.Mesh(geometry, material);
      //     mountain.position.z = 0;
      //     // mountain.position.y = 0;
      //     // mountain.rotation.x = Math.PI / 4;
      //     // mountain.rotation.y = Math.PI / 4;
      //     // mountain.rotation.z = Math.PI / 4;
      //     mountain.rotation.axis.x = 1;
      //     mountain.rotation.axis.z = 0;
      //     mountain.rotation.angle = -90;
      //     this.meshVisualizerTif.add(mountain);
      //   }).catch(err => {
      //     debugger
      //   });
      // };
      // readGeoTif();
      // //       coordinatetype: "EPSG:WGS 84"
      // // demid: "cd40928f53e14bbf83fc185bd6ce9816"
      // // name: "精细化地形"
      // // range: "[113.2521097,23.08407111,113.2549597,23.08589111]"
      // // remotepath: "/ProjectPath/1417437301540413442/1417437436236292098/1405431307315449999/cd40928f53e14bbf83fc185bd6ce9815/cd40928f53e14bbf83fc185bd6ce9816.tif"
      // // remotetime: "2021-12-21 00:00:00"
      // // stageid: "cd40928f53e14bbf83fc185bd6ce9815"
      // // stagename: "20211221"
      // let url = this.newBaseUrl + data[0].remotepath
      // this.viewer.terrainProvider = new Cesium.CesiumTerrainProvider({
      //   url: url,
      //   minimumLevel: 0,
      //   maximumLevel: 15,
      //   // requestWaterMask : true,//开启法向量
      //   // requestVertexNormals : true//开启水面特效
      // });
    },
    removeTerrain() {
      // this.viewer.terrainProvider = Cesium.createWorldTerrain();
    },

    /**
     * 添加污染物实体 - 钻井,监测井等
     */
    addPollutantEntity(item){
      debugger
      let name = item.drillDTO[0].properties.name
      console.log(name);
      item.samplingDTO.forEach((ele,index)=>{
        let lon = ele.geometry.coordinates[0][0];
        let lat = ele.geometry.coordinates[0][1];
        let depth = JSON.parse(ele.properties.depth);
        // 铅
        let type = ele.properties.chemname
        let vals = ele.properties.vals
        let itemId = name + "_" + ele.properties.analysisid
        this.pollutantId.set(itemId,itemId)
        this.createPollutantPoint(lon,lat,depth,type,vals,itemId)
      })
    },
    /**
     * 污染物实体创建
     */
    createPollutantPoint(x,y,depth,type,vals,dataId){
      debugger
      let materialColor = null
      if(vals >0 && vals <= 50){
        materialColor = Cesium.Color.GREEN.withAlpha(1);
      }else if(vals > 50 && vals <= 100){
        materialColor = Cesium.Color.YELLOW.withAlpha(1);
      }else if(vals > 100 && vals <= 200){
        materialColor = Cesium.Color.RED.withAlpha(1);
      }else if(vals > 200 && vals <= 500){
        materialColor = Cesium.Color.BLUE.withAlpha(1);
      }else if(vals > 500){
        materialColor = Cesium.Color.BLACK.withAlpha(1);
      }
      this.viewer.entities.add({
        name: type + "-" + dataId,
        id: dataId,
        position: Cesium.Cartesian3.fromDegrees(x, y, depth),
        point:{
          color:materialColor,
          pixelSize: 10,
          outlineColor: Cesium.Color.WHITE,
          outlineWidth: 1,
          disableDepthTestDistance: Number.POSITIVE_INFINITY,
        }
      })

    },
    /**
     * 添加钻孔实体
     */
    addCylinderEntity(item) {
      // 只传入单个对象
      item.drillDTO.forEach((ele, index) => {
        debugger;
        let lon = ele.geometry.coordinates[0][0];
        let lat = ele.geometry.coordinates[0][1];
        let startDepth = ele.properties.start_depth;
        let endDepth = ele.properties.end_depth; //结束深度
        let geoMaterial = ele.properties.geo_material; //土壤类型
        let name = ele.properties.name;
        // 每次绘制一个钻孔，创建一个Id
        this.drillId.set(name + index, name + index);
        this.createCylinder(
          lon,
          lat,
          startDepth,
          endDepth,
          geoMaterial,
          name,
          index
        );
      });
    },
    /**
     * 添加监测井取样实体
     */
    addWellEntity(item) {
      item.drillDTO.forEach((ele, index) => {
        debugger;
        let lon = ele.geometry.coordinates[0][0];
        let lat = ele.geometry.coordinates[0][1];
        let startDepth = 0;
        let endDepth = ele.properties.depth; //结束深度
        let geoMaterial = ele.properties.geo_material; //土壤类型
        let name = ele.properties.name;
        // 每次绘制一个钻孔，创建一个Id
        this.wellId.set(name + index, name + index);
        this.createCylinder(
          lon,
          lat,
          startDepth,
          endDepth,
          geoMaterial,
          name,
          index
        );
      });
    },
    /**
     * 创建钻孔实体
     */
    createCylinder(x, y, startDepth, endDepth, material, drillName, index) {
      let materialColor = "";
      switch (material) {
        case "杂填土":
          materialColor = Cesium.Color.GREEN.withAlpha(1);
          break;
        case "粘质粉土":
          materialColor = Cesium.Color.YELLOW.withAlpha(1);
          break;
        case "粉土":
          materialColor = Cesium.Color.RED.withAlpha(1);
          break;
        case "粉质粘土":
          materialColor = Cesium.Color.BLUE.withAlpha(1);
          break;
      }
      let start = parseFloat(startDepth);
      let end = parseFloat(endDepth);
      let altitude = parseFloat((end - start) / 2 + start);
      this.viewer.entities.add({
        name: "startDepth:" + startDepth + " endDepth:" + endDepth,
        id: drillName + index,
        position: Cesium.Cartesian3.fromDegrees(x, y, altitude),
        cylinder: {
          length: parseFloat(endDepth) - parseFloat(startDepth),
          topRadius: 1.5,
          bottomRadius: 1.5,
          material: materialColor,
          outline: false,
        },
      });
    },
    /**
     * 移除钻孔实体
     */
    removeCylinder(entityId) {
      debugger;
      let cylinderEntID = this.viewer.entities.getById(entityId);
      this.viewer.entities.remove(cylinderEntID);
    },

    /**
     * 移除单个实体
     * @param {*} entity
     */
    removeEntity(entity) {
      debugger;
      let entityId = this.viewer.entities.getById(entity);
      this.viewer.entities.remove(entityId);
    },

    /**
     * 添加线墙图层ERT
     */
    addWallEntity(item) {
      debugger;
      // 传入的为数组时使用
      // lineArr.forEach((item) => {
      //   let coordArr = item.geometry.coordinates;
      //   let positionArr = [].concat.apply([], coordArr);
      //   let name = item.properties.name;
      //   //wallLineArr = coord
      //   let imageUrl = this.newBaseUrl + item.properties.pic;
      //   this.ertId.set(name, name);
      //   this.createWall(positionArr, imageUrl, name);
      // });

      // 只传入对象时使用
      let coordArr = item.geometry.coordinates;
      let positionArr = [].concat.apply([], coordArr);
      let name = item.properties.name;
      //wallLineArr = coord
      let imageUrl = this.newBaseUrl + item.properties.pic;
      this.ertId.set(name, name);
      this.createWall(positionArr, imageUrl, name);
    },
    /**
     * 移除线墙图层 ERT
     */
    removeWallEntity(lineArr) {
      lineArr.forEach((item) => {
        let wallEntID = this.viewer.entities.getById(item.properties.name);
        this.viewer.entities.remove(wallEntID);
      });
    },
    /**
     * 创建线墙实体 ERT
     */
    createWall(positionArr, imageUrl, name) {
      // imageUrl = "http://localhost:8080/test.png"
      let colorWall = this.viewer.entities.add({
        label: {
          text: name,
          show: true,
          showBackground: true,
          font: "14px monospace",
          horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
          verticalOrigin: Cesium.VerticalOrigin.TOP,
          pixelOffset: new Cesium.Cartesian2(15, 0),
        },
        id: name,
        //position: Cesium.Cartesian3.fromDegrees(x, y, z),
        wall: {
          positions: Cesium.Cartesian3.fromDegreesArrayHeights(positionArr),
          material: new Cesium.ImageMaterialProperty({
            image: imageUrl,
            transparent: true,
          }),
        },
      });
      // console.log(this.viewer.entities);
    },
    /**
     * 添加面图层
     */
    addPolygonEntity(item) {
      // polygonArr.forEach((item) => {
      //   let materialUrl = this.newBaseUrl + item.properties.pic;
      //   let coordArr = item.geometry.coordinates;
      //   let newCoordArr = coordArr.filter(
      //     (value, index) => index < coordArr.length - 1
      //   );
      //   let positionArr = [].concat.apply([], newCoordArr);
      //   let name = item.properties.name;
      //   this.emId.set(name, name);
      //   this.createPolygon(positionArr, materialUrl, name);
      // });

      // 单个对象时使用
      let materialUrl = this.newBaseUrl + item.properties.pic;
      let coordArr = item.geometry.coordinates;
      let newCoordArr = coordArr.filter(
        (value, index) => index < coordArr.length - 1
      );
      let positionArr = [].concat.apply([], newCoordArr);
      let name = item.properties.name;
      this.emId.set(name, name);
      this.createPolygon(positionArr, materialUrl, name);
    },
    /**
     * 移除面图层
     */
    removePolygonEntity(polygonArr) {
      polygonArr.forEach((item) => {
        let polyEntID = this.viewer.entities.getById(item.properties.name);
        this.viewer.entities.remove(polyEntID);
      });
    },
    /**
     * 创建面实体
     */
    createPolygon(positionArr, url, name) {
      let polygon = this.viewer.entities.add({
        id: name,
        polygon: {
          //按逆时针方向排序，从左下角开始
          hierarchy: Cesium.Cartesian3.fromDegreesArray(positionArr),
          material: new Cesium.ImageMaterialProperty({
            image: url,
            transparent: true,
            color: Cesium.Color.WHITE,
          }),
        },
      });
    },
  },
};
